from django.contrib.auth import authenticate, login
from django.shortcuts import render
from django.http import JsonResponse
from system.models import Users,Role,Menu
from django.db.models import Q
from django.core.paginator import Paginator
from cmdb.settings import default_page,default_limit,default_password
from django.contrib.auth.hashers import make_password
from utils.request_util import save_login_log
from django.http import StreamingHttpResponse
from django.contrib.auth.decorators import login_required
from utils.findButtonPer import findButtonPermission

def user_page(request):
    # 这里进行判断权限部分
    role_obj = request.user.role.first()
    result = findButtonPermission(role_obj=role_obj,key='users')
    return render(request, 'system/user/user.html',result)

def userAdd_page(request):
    return render(request, 'system/user/insert.html')
    
def userEdit_page(request):
    return render(request, 'system/user/edit.html')

def login_logic(request):
    # 需要判断获取类型,这里POST为表单登录提交类型，必须为大写
    if(request.method=='POST'):
        u_name = request.POST.get('username')
        u_pass = request.POST.get('password')
        user_obj = authenticate(username=u_name, password=u_pass)
        if not user_obj or user_obj.is_active==False:
            return JsonResponse({'code':4000,'msg':'用户名或者密码错误或被禁止登陆!'})
        else:
            login(request, user_obj)
            # 进行登录记录
            save_login_log(request=request)
            # 通过user查找正常显示存在的role角色的id
            # user_obj = Users_model.objects.get(user_code=code)
            # role_list = user_obj.user_role.filter().values_list('id', flat=True)
            # 这里用以查询他对于表单拥有的操作权限
            # menu_list = Menu_model.objects.filter(role_model__id__in=role_list).distinct().exclude(menu_marital__in=['01', '02'])
            return JsonResponse({'code':200,'msg':'登录成功!'})
    else:
        return render(request, 'login.html')


# 获得登陆者的信息，查询其拥有的菜单权限
@login_required()
def getUserInfoData(request):
    roleId_list=request.user.role.filter().values_list('id', flat=True)
    # 通过角色查拥有的菜单权限,所拥有的目录，菜单权限，用以前台渲染数据
    menuList = Menu.objects.filter(role__id__in=roleId_list).exclude(menu_type=2).distinct().order_by('sort')
    list_menu=[]
    m_obj = Menu()
    for i in menuList:
        dict = {}
        if i.parent_id is None:
            dict['id'] = i.id
            dict['icon'] = i.icon
            dict['fontFamily'] = 'ok-icon'
            dict['title'] = i.name 
            dict['href'] = i.path 
            dict['spread'] = False
            if i.parent_id is not None:
                dict['parent'] = int(i.parent_id)
            else:
                dict['parent'] = None
            list_menu.append(dict)
        else:
            dict['id'] = i.id
            dict['icon'] = i.icon
            dict['fontFamily'] = 'ok-icon'
            dict['title'] = i.name 
            dict['href'] = i.path 
            dict['spread'] = False
            dict['parent'] = int(i.parent_id)
            list_menu.append(dict)
    res = []
    for con in list_menu:
        res.append(con)
    Result = {'code': 0, 'msg': '成功！', 'data': res}
    return JsonResponse(Result)

@login_required()
def  getUserData(request):
    try:
        users_list =Users.objects.all()
        users_count =Users.objects.count()
        list_user=[]
    except Exception as e:
        return JsonResponse({'code': 4000, 'msg': '查询数据失败！'})
    for i in users_list:
        user_obj = Users.objects.get(id=i.id)
        roles_name = user_obj.role.filter().values_list('name',flat=True)
        roles_id = user_obj.role.filter().values_list('id', flat=True)
        roles = list(roles_name)
        dict = {}
        dict['id'] = i.id
        dict['username'] = i.username
        dict['name'] = i.name 
        dict['email'] = i.email
        dict['mobile'] = i.mobile 
        dict['dept_id'] = i.dept.id
        dict['dept_name'] = i.dept.name
        dict['gender'] = i.gender
        dict['role_display'] = roles
        dict['roles_id'] = list(roles_id)
        dict['is_active'] = i.is_active
        # dict['create_datetime'] = i.create_datetime.strftime("%Y-%m-%d %H:%M:%S")
        # dict['update_datetime'] = i.update_datetime.strftime("%Y-%m-%d %H:%M:%S")
        dict['description'] = i.description
        list_user.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    if pageIndex is None:
        pageIndex = default_page
    if pageSize is None:
        pageSize = default_limit
    pageInator = Paginator(list_user, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    Result = {'code': 0, 'msg': '成功！','count':users_count, 'data': res}
    return JsonResponse(Result)


def addUserData(request):
    get_name = request.POST.get('name')
    # 这里前端获取下拉框的时候，传上来默认就是名字就叫select,这里对应的是菜单权限
    get_role = request.POST.get('role')
    get_dept = request.POST.get('dept')
    get_email = request.POST.get('email')
    get_mobile = request.POST.get('mobile')
    get_gender = request.POST.get('gender')
    get_description = request.POST.get('description')
    roles = str(get_role).split(',')
    try:
        obj = Users.objects.create(name=get_name,email=get_email,dept_id=get_dept,mobile=get_mobile,gender=get_gender,
        description=get_description,creator_id=request.user.id,dept_belong_id=request.user.dept.id)
        #这里多对多的情况下。
        role_obj = Role.objects.filter(id__in=roles)
        obj.role.add(*role_obj)
        obj.password = make_password(default_password)
        obj.save()
    except Exception as e:
        print(e)
        return JsonResponse({'code': 4002, 'msg': '创建用户失败，请联系管理员！'})
    Result = {'code': 0, 'msg': '创建用户成功'}
    return JsonResponse(Result)

@login_required()
def editUserData(request,id):
    name = request.POST.get('name')
    role = request.POST.get('role') #这里前段插件不知道为什么自动命名为select，应该是可以改的
    dept = request.POST.get('dept')
    email = request.POST.get('email')
    mobile = request.POST.get('mobile')
    gender = request.POST.get('gender')
    is_active = request.POST.get('is_active')
    description = request.POST.get('description')
    roles = str(role).split(",")
    # 注意这里为什么不能用传统的xx.objects.filter(pk=id).update(),然后直接清空多对多的情况，这样不能保证提交的时候是一致性
    try:
        obj = Users.objects.get(pk=id)
        obj.name=name
        obj.email=email
        obj.mobile=mobile
        obj.gender=gender
        obj.dept_id=dept
        obj.is_active=is_active
        obj.modifier=request.user.id
        obj.description=description
        role_obj = Role.objects.filter(id__in=roles)
        obj.role.clear()
        obj.role.add(*role_obj) # 这里应该是对象
        obj.save()
    except Exception as e:
        return JsonResponse({'code': 4002, 'msg': '修改用户信息失败！'})
    Result = {'code': 0, 'msg': '修改成功'}
    return JsonResponse(Result)



def delUserData(request,id):
    try:
        user_obj = Users.objects.get(pk=id)
    except Exception as e:
        return JsonResponse({'code': 202, 'msg': '未找到删除对象！'})
    if user_obj.is_active==True:
        return JsonResponse({'code': 203, 'msg': '在职人员不可删除！'})
    try:
        user_obj.delete()
    except Exception as e:
        return JsonResponse({'code': 202, 'msg': '删除员工失败！'})
    return JsonResponse({'code': 0, 'msg':'删除成功！'})

@login_required()
def queryUserData(request):
    name = request.GET.get('searchName')
    try:
        if len(name)==0:
            user_list = Users.objects.filter()
        else:
            user_list = Users.objects.filter(Q(name__contains=name)|Q(mobile__contains=name)|Q(email__contains=name))
        users_count = len(list(user_list))
    except Exception as e:
        print(e)
        return JsonResponse({'code': 201, 'msg': 'user查询模块出现问题，请联系管理员！'})
    list_user=[]
    for i in user_list:
        user_obj = Users.objects.get(id=i.id)
        roles_name = user_obj.role.filter().values_list('name',flat=True)
        roles_id = user_obj.role.filter().values_list('id', flat=True)
        roles = list(roles_name)
        dict = {}
        dict['id'] = i.id
        dict['username'] = i.username
        dict['name'] = i.name 
        dict['email'] = i.email
        dict['mobile'] = i.mobile 
        dict['gender'] = i.gender
        dict['role_display'] = roles
        dict['roles_id'] = list(roles_id)
        dict['is_active'] = i.is_active
        # dict['create_datetime'] = i.create_datetime.strftime("%Y-%m-%d %H:%M:%S")
        # dict['update_datetime'] = i.update_datetime.strftime("%Y-%m-%d %H:%M:%S")
        dict['description'] = i.description
        list_user.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    if pageIndex is None:
        pageIndex = default_page
    if pageSize is None:
        pageSize = default_limit
    pageInator = Paginator(list_user, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    Result = {'code': 0, 'msg': '成功！','count':users_count, 'data': res}
    return JsonResponse(Result)


# def downUserTemplate(request):
#     file_name = "userImport_template.xlsx"  # 文件名
#     base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # 项目根目录
#     file_path = os.path.join(base_dir, 'upload', 'export_template', file_name)  # 下载文件的绝对路径
#     def file_iterator(file_path, chunk_size=512):
#          """
#          文件生成器,防止文件过大，导致内存溢出
#          :param file_path: 文件绝对路径
#          :param chunk_size: 块大小
#          :return: 生成器
#          """
#          with open(file_path, mode='rb') as f:
#              while True:
#                  c = f.read(chunk_size)
#                  if c:
#                      yield c
#                  else:
#                      break
 
#     # 设置响应头
#     # StreamingHttpResponse将文件内容进行流式传输，数据量大可以用这个方法
#     response = StreamingHttpResponse(file_iterator(file_path))
#     # 以流的形式下载文件,这样可以实现任意格式的文件下载
#     response['Content-Type'] = 'application/octet-stream'
#     # Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名
#     response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)
#     return response